import * as React from 'react';
import { Col, DatePicker } from 'antd';
import * as moment from 'moment';
interface Props extends React.Props<any> {
  label?: string;
  value?: any;
  defaultValue?: string;
  error?: string;
  col?: number;
  disabled?: boolean;
  required?: boolean;
  modelKey: string;
  dateFormat: string;
  placeholder?: string;
  onChange?: (e: string, key: string) => void;
}
export class SDatePicker extends React.PureComponent<Props, any> {
  static defaultProps = {
    dateFormat: 'YYYY-MM-DD'
  }
  constructor(props) {
    super(props);
    this.state = {
      stateDefaultValue: null
    }
  }
  componentDidMount = () => {
    const { defaultValue, modelKey, dateFormat} = this.props;
    if (defaultValue) {
      this.setState({stateDefaultValue: moment(defaultValue, dateFormat)})
      this.props.onChange!(defaultValue, modelKey);
    }
  }
  datePickerChange(e) {
    const { modelKey } = this.props;
    const date: string =  moment(e).format(this.props.dateFormat);
    this.props.onChange!(date, modelKey);
  }
  render() {
    const { label, col, disabled, required, error, placeholder } = this.props;
    return (
      <div className='s-datePicker smart-form'>
        <Col span={col}>
          {
            label ?
            <label className='label'>
              <span>{label}</span>
              {required ? <i className='required'>*</i> : null}
            </label> : null
          }
          <div className={error ? 'form-error' : ''}>
            <DatePicker
              defaultValue={this.state.stateDefaultValue}
              disabled={disabled}
              style={{width: '100%'}}
              placeholder={placeholder}
              onChange={e => this.datePickerChange(e)}
            />
          </div>
          <em className='note-error'>{error}</em>
        </Col>
      </div>
    )
  }
}